/* -----------------
* brief
* 1. this is code gen by tools
* 2. mvc code are driver by the model defined with the same filename,
	 for example:
	 there is a Xmodel struct define in xmodel.go file, after the script run (lego model-mvc module_name xmodel)
     it will auto create the code under the module's path
	 m --> xmodel.go
	 v --> view
	 c --> xmodel_ctrl
* 3. you should modify this code if it doesn't satisfy your purpose
*/

package controller

import (
	"encoding/json"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"github.com/valyala/fasthttp"
	"saas_sys_base/common"
	. "saas_sys_base/modules/eshop/models"
	. "saas_sys_base/modules/eshop/service"
	. "saas_sys_base/modules/product/models"
	. "saas_sys_base/modules/product/service"
)

type ProductCateCtrl struct {
	shopService EShopService
	service ProductCateService
}

func init() {
	vc := new(ProductCateCtrl)
	_ctrlList = append(_ctrlList, vc)
}

func (vc *ProductCateCtrl) CtrlInfo() string {
	return "ProductCateCtrl"
}

func (vc *ProductCateCtrl) RoutInit() {
	// 列表页面
	lego.GET("/admin/product/ProductCate/listpage", vc.ListPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	lego.GET("/admin/product/ProductCate/listjson", vc.ListJson, lego.LEGO_SESSION_TYPE_ADMIN, false)
	// 编辑页面
	lego.GET("/admin/product/ProductCate/editpage", vc.GetEditPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	lego.POST("/admin/product/ProductCate/editpage", vc.PostEditPage, lego.LEGO_SESSION_TYPE_ADMIN, false)
	// 删除
	lego.POST("/admin/product/ProductCate/del", vc.DelRecode, lego.LEGO_SESSION_TYPE_ADMIN, false)

	//租户管理端接口
	lego.GET("/admin/product/ProductCate/listpage_saas", vc.ListPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, false)
	lego.GET("/admin/product/ProductCate/listjson_saas", vc.ListJson_Saas, lego.LEGO_SESSION_TYPE_ADMIN, false)

	lego.GET("/admin/product/ProductCate/editpage_saas", vc.GetEditPage_Saas, lego.LEGO_SESSION_TYPE_ADMIN, false)

	/*
	* 商家小程序API
	*/
	//列表
	lego.APIGET("/api/Product/ProductCate/CateList", vc.TenantListJson, true)
	lego.APIPOST("/api/Product/ProductCate/EditOrCreate", vc.PostEditPage, true)

}
/* 列表接口
* params:
  ---
*/
func (vc *ProductCateCtrl) TenantListJson(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		//:saas管理端使用代码，使用时将注释解开 sessionData := common.GetSessionData(&ctxExt)
		//:appwho := sessionData.AppTokenWho
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		// 表单校验
		type ReqParams struct {
			Keyword string // 关键字查询

			Order      string `vd:"$=='' || $=='asc' || $=='desc'"`
		}
		req := ReqParams{
			Keyword:    string(ctxExt.Peek("keyword")),
			Order:      string(ctxExt.Peek("order")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务查询
		if list, total, err := vc.service.ListProductCateByTenant(req.Keyword, appwho.TenantId, req.Order); err != nil {

			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 列表接口
* params:
  ---
*/
func (vc *ProductCateCtrl) ListJson(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		//:saas管理端使用代码，使用时将注释解开 sessionData := common.GetSessionData(&ctxExt)
		//:appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			Keyword string // 关键字查询
			Page    int    `vd:"$>0"` // 分页
			PSize   int    `vd:"$>0"` // 分页大小

			OrderField string
			Order      string `vd:"$=='' || $=='asc' || $=='desc'"`
		}
		req := ReqParams{
			Keyword:    string(ctxExt.Peek("keyword")),
			Page:       utils.BytesToInt(ctxExt.Peek("page")),
			PSize:      utils.BytesToInt(ctxExt.Peek("limit")),
			OrderField: string(ctxExt.Peek("order_field")),
			Order:      string(ctxExt.Peek("order")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务查询
		if list, total, err := vc.service.ListProductCate(req.Keyword, req.Page, req.PSize, req.OrderField, req.Order); err != nil {
			code = 100
			msg = "fail"
			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *ProductCateCtrl) ListPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("product/view/ProductCate/list.html", data)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *ProductCateCtrl) GetEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		target := vc.service.GetProductCateById(req.Id)
		data["detail"] = target
		break
	}
	ctxExt.HTML("product/view/ProductCate/edit.html", data)
	return
}

/* 数据编辑
* params:
  ---
*/
func (vc *ProductCateCtrl) PostEditPage(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := "添加成功"

	for {

		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			//#ModelEditFormDefined#
			Id           int64        `json:"id,string"`
			CateName  string       `json:"cate_name"`
			EShopId      int64        `json:"shop_id,string"`
		}
		var req ReqParams
		requestByte := ctxExt.PostBody()
		err := json.Unmarshal(requestByte, &req)
		if err != nil {
			code = 100
			msg = "参数错误"
			break
		}
		tenantShops := vc.shopService.ListByTenandId(appwho.TenantId)
		if req.EShopId > 0 {
			anyFlag, err := utils.SliceAny(tenantShops, func(elem interface{}) bool {
				v := elem.(*EShop)
				if v.Id == req.EShopId {
					return true
				}
				return false
			})
			if err != nil {
				code = 100
				msg = "参数错误"
				break
			}
			if !anyFlag {
				code = 100
				msg = "店铺不是自己的"
				break
			}
		} else {
			if tenantShops[0].TenantId == appwho.TenantId {
				req.EShopId = tenantShops[0].Id
			} else {
				code = 100
				msg = "请先添加店铺"
				break
			}
		}

		tenantShop := vc.shopService.GetEShopByTenantId(appwho.TenantId)

		if tenantShop == nil{
			code = 100
			msg = "店铺信息不存在"
			break
		}
		// 业务处理
		//recode := vc.service.GetProductCateById(req.Id)
		recode := vc.service.TenantRecodeById(req.Id, tenantShop.Id)
		if recode == nil {
			// 新建
			recode := new(ProductCate)
			//#ModelFiledMapper#'
			recode.Id = req.Id

			recode.EShopId = req.EShopId
			recode.TenantId = appwho.TenantId
			recode.CateName = req.CateName

			if false == vc.service.SaveProductCate(recode) {
				code = 100
				msg = "false"
				break
			}
		} else {
			//#ModelFiledMapper#
			recode.Id = req.Id
			recode.EShopId = req.EShopId
			recode.TenantId = appwho.TenantId
			recode.CateName = req.CateName

			if false == vc.service.UpdateProductCate(recode) {
				code = 100
				msg = "false"
				break
			}
		}
		break
	}
	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

/* 删除数据记录
* params:
  ---
*/
func (vc *ProductCateCtrl) DelRecode(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	data := make(map[string]interface{})

	code := 0
	msg := ""
	for {
		// 表单校验
		type ReqParams struct {
			Id int64 `vd:"$>0"` // 记录id
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		// 业务删除
		target := vc.service.GetProductCateById(req.Id)
		if target == nil {
			code = 100
			msg = "记录不存在"
			break
		}

		if false == vc.service.DelProductCateById(target.Id) {
			code = 100
			msg = "操作失败"
			break
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	response["data"] = data
	ctxExt.JSON(200, response)
	return
}

//租户管理端 for saas ********
/* 列表接口
* params:
  ---
*/
func (vc *ProductCateCtrl) ListJson_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	response := make(map[string]interface{})
	code := 0
	msg := ""

	for {
		sessionData := common.GetSessionData(&ctxExt)
		appwho := sessionData.AppTokenWho

		// 表单校验
		type ReqParams struct {
			Keyword string // 关键字查询
			Page    int    `vd:"$>=0"` // 分页
			PSize   int    `vd:"$>0"`  // 分页大小

			OrderField string
			Order      string `vd:"$=='' || $=='asc' || $=='desc'"`
		}
		req := ReqParams{
			Keyword:    string(ctxExt.Peek("keyword")),
			Page:       utils.BytesToInt(ctxExt.Peek("page")),
			PSize:      utils.BytesToInt(ctxExt.Peek("limit")),
			OrderField: string(ctxExt.Peek("order_field")),
			Order:      string(ctxExt.Peek("order")),
		}
		if err := lego.Validate(req); err != nil {
			code = 100
			msg = err.Error()
			break
		}

		// 业务查询
		if list, total, err := vc.service.ListProductCateByWho(appwho, req.Keyword, req.Page, req.PSize, req.OrderField, req.Order); err != nil {
			lego.LogError(err)
		} else {
			response["count"] = total
			response["data"] = list
		}
		break
	}

	response["code"] = code
	response["msg"] = msg
	ctxExt.JSON(200, response)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *ProductCateCtrl) ListPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量
		break
	}
	ctxExt.HTML("product/view/ProductCate/list_saas.html", data)
	return
}

/* 添加数据记录
* params:
  ---
*/
func (vc *ProductCateCtrl) GetEditPage_Saas(ctx *fasthttp.RequestCtx) {
	ctxExt := lego.RequestCtxExtent{ctx}
	data := make(map[string]interface{})
	for {
		sessionData := common.GetSessionData(&ctxExt) //
		appwho := sessionData.AppTokenWho
		data["Who"] = appwho //adminSaas(租户管理端)使用的变量

		type ReqParams struct {
			Id int64 // 记录id，为空则新建，否则为编辑
		}
		req := ReqParams{
			Id: utils.BytesToInt64(ctxExt.Peek("id")),
		}
		if err := lego.Validate(req); err != nil {
			break
		}
		target := vc.service.GetProductCateById(req.Id)
		data["detail"] = target
		break
	}
	ctxExt.HTML("product/view/ProductCate/edit_saas.html", data)
	return
}
